"""
    Author:
    Date: 2019-05-30

    资料管理类
"""

from apps.gma import helpers as gma_helpers
from entities.consts import *
from utils import db

TABLE_NAME = 'cmf_users_profile'


def get_profile_count_by_auth_status(status, request=None):
    """ 根据审核状态获取资料数量 """
    apps_condition = gma_helpers.build_app_filter_condition_for_request(request)
    sql = f'''
        SELECT      COUNT(*) AS profile_count
        FROM        {TABLE_NAME} AS p
        JOIN        cmf_users_auth AS a ON p.uid=a.uid
        JOIN        cmf_users AS u ON u.id=p.uid
        WHERE       {apps_condition} AND
                    p.status={status} AND
                    a.status={AUTH_STATUS_CERTIFIED};
    '''
    data = db.query_data_from_db(sql)
    return data[0]['profile_count'] if data else 0


def get_profile_list_by_auth_status(status, count, request=None):
    """ 根据审核状态获取资料列表 """
    apps_condition = gma_helpers.build_app_filter_condition_for_request(request)
    sql = f'''
        SELECT      p.*,
                    u.avatar,
                    u.nickname
        FROM        {TABLE_NAME} AS p
        JOIN        cmf_users AS u ON p.uid=u.id
        JOIN        cmf_users_auth AS a ON p.uid=a.uid
        WHERE       {apps_condition} AND
                    p.status={status} AND
                    a.status={AUTH_STATUS_CERTIFIED}
        ORDER BY    update_time DESC
        LIMIT       {count};
    '''
    data = db.query_data_from_db(sql)
    return data if data else []


def get_profile_info(pid):
    """ 根据id查找资料信息 """
    sql = f'''
        SELECT      *
        FROM        {TABLE_NAME}
        WHERE       id={pid}
        LIMIT       1;
    '''
    data = db.query_data_from_db(sql)
    return data[0] if data else None


def update_profile_auth_status(vid, auth_status):
    """ 更新资料的认证状态 """
    sql = f'''
        UPDATE      {TABLE_NAME}
        SET         status={auth_status}
        WHERE       id={vid}
        LIMIT       1;
    '''
    affected_rows = db.execute_sql(sql)
    return affected_rows == 1


def get_user_authing_profile_by(uid):
    """ 根据uid查找待审核的资料信息 """
    sql = f'''
        SELECT      *
        FROM        {TABLE_NAME}
        WHERE       uid={uid} AND
                    status={AUTH_STATUS_WAITING}
        LIMIT       1;
    '''
    data = db.query_data_from_db(sql)
    return data[0] if data else None


if __name__ == '__main__':
    print('ok')
